//
//  NetWorkHandler.m
//  UI19_网络封装(delegate回调)
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetWorkHandler.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"

@implementation NetWorkHandler

/** 通过NSURLSession实现网络请求 */
- (void)netWorkHandlerJSONWithURL:(NSString *)urlString {
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    
    if (isExistenceNetwork) {
        
        // 将字符串进行转码(URL中不能含有中文等字符)
        NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        // URL
        NSURL *url = [NSURL URLWithString:temp];
        
        // session
        NSURLSession *session = [NSURLSession sharedSession];
        
        // add task
        NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
            NSString *behind = @".data";
            NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetWorkHandler md5HexDigest:urlString],behind]];
            
            [data writeToFile:path  atomically:YES];
            
            //返回主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 解析
                NSError *errorOfJSON = nil;
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorOfJSON];
                
                if ([self.delegate respondsToSelector:@selector(handlerDidComplete:)]) {
                    
                    [self.delegate handlerDidComplete:result];
                }
            });
            
        }];
        
        // 任务开始
        [task resume];
        
    } else {
        
        NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetWorkHandler md5HexDigest:urlString],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        if (data == nil) {
            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"NoNet" object:nil];
            
            return;
            
        } else {
            
            NSError *errorOfJSON = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorOfJSON];
            
            if ([self.delegate respondsToSelector:@selector(handlerDidComplete:)]) {
                
                [self.delegate handlerDidComplete:result];
            }
        }
    }
    
}

+ (void)handlerJSONWithURL:(NSString *)urlString delegate:(id<NetWorkHandlerDelegate>)delegate {
    
    NetWorkHandler *handler = [[NetWorkHandler alloc] init];
    
    handler.delegate = delegate;
    
    [handler netWorkHandlerJSONWithURL:urlString];
    
    
}

/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
    
}










@end
